package com.mynovamobile.android;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.EditText;

public class PinLogin extends Activity {
	private final static String TAG = "[PinLogin]";
	private MNMRequest authPin;
	private MNMReauthorizationController reauthController;
	private boolean noAuthNeeded;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pin_login);

		authPin = new MNMRequest(this);
		final MNMUserDefaults userData = MNMUserDefaults.getInstance(this);
		final PinLogin pinContext = this;
		final EditText pinField = (EditText) findViewById(R.id.pin_login_field);
		final ImageButton b = (ImageButton) findViewById(R.id.pin_login_loginButton);
		
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String pin = pinField.getText().toString();
				noAuthNeeded = false;
				
				if (pin.length() == 4) {
					authPin.addData("pin", pin);
					authPin.addData("uid", userData.getMNMUserID());
					String url = getString(R.string.protocol)
							+ getString(R.string.hostname)
							+ getString(R.string.auth_pin_url);
					String authenticationStatus;
					try {
						JSONObject responseData = authPin.executeRequest(url);
						authenticationStatus = responseData.getString("response_type");
					} catch (ClientProtocolException e) {
						Log.e(TAG, "Encountered: " + e.toString());
						new MNMMessage(pinContext, "Request Error", e.getMessage(), MNMMessage.ERROR);
						return;
					} catch (UnsupportedEncodingException e) {
						Log.e(TAG, "Encountered: " + e.toString());
						new MNMMessage(pinContext, "Invalid Encoding", e.getMessage(), MNMMessage.ERROR);
						return;
					} catch (IOException e) {
						Log.e(TAG, "Encountered: " + e.toString());
						new MNMMessage(pinContext, "Network I/O Error", e.getMessage(), MNMMessage.ERROR);
						return;
					} catch (JSONException e) {
						Log.e(TAG, "Encountered: " + e.toString());
						new MNMMessage(pinContext, "Parse Error", e.getMessage(), MNMMessage.ERROR);
						return;
					}
					if (authenticationStatus.equals("success")) {
						Log.i(TAG, "User succeeded PIN authentication");
						//pinContext.verifyUserData();
						reauthController = new MNMReauthorizationController(pinContext);
						if (reauthController.needsReauthorization()) {
							Log.v(TAG, "reauthController determines reauthorization is needed");
							reauthController.reauthorize();
						} else {
							// Will reach here if there are no user data fields to reauthorize
							// TODO: (tclift01) Log them into the application
							Log.v(TAG, "reauthController determines NO reauthorization is needed!");
							noAuthNeeded = true;
							loadMainApplication();
						}
					} else {
						Log.w(TAG, "User failed PIN authentication.");
						new MNMMessage(pinContext, "Incorrect Pin", "Your supplied PIN was incorrect.", MNMMessage.ERROR);
					}
				} else {
					new MNMMessage(pinContext, "Invalid Pin", "Your supplied PIN must be 4 numbers long.", MNMMessage.ERROR);
				}
			}
		});
	}
	
	private void loadMainApplication() {
		// TODO: Change this intent to be the main application
		new MNMMessage(this, "Main Application Launch", "WOOOOO!!!");
		Log.v(TAG, "Called loadMainApplication, STARTING NEW ACTIVITY");
		// startActivity(new Intent(getApplicationContext(), null));
	}
	
	@Override
	public void onPause() {
		super.onPause();
		if (reauthController != null) {
			if (reauthController.getStepCount() == 0) {
				finish();
			}
		} else if (noAuthNeeded) {
			finish();
		}
	}
	
	@Override
	public void onResume() {
		Log.v(TAG, "Called onResume");
		super.onResume();
		if (reauthController != null) {
			if (reauthController.getStepCount() > 0) {
				Log.v(TAG + ".onResume()", "More authorization steps needed...");
				reauthController.reauthorize();
			} else {
				Log.v(TAG, "No more authorization steps needed!");
				loadMainApplication();
			}
		}
	}
}
